package dao;

import model.Administrator;
import tool.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdministratorDao {
    Util util = new Util();
    Connection con = null;

    public void addAdministrator(Administrator administrator) {
        con = util.getConnection();
        String sql = "insert into administrator (name,password) values (?,?)";
        try {
            PreparedStatement ptmt = con.prepareStatement(sql);

            ptmt.setString(1, administrator.getName());
            ptmt.setString(2, administrator.getPassword());
            ptmt.executeUpdate();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    public int Login(String name, String password) {
        int num = 0;
        String p = null;
        con = util.getConnection();
        String sql = "select id,password from administrator where name=?";
        try {
            PreparedStatement ptmt = con.prepareStatement(sql);
            ptmt.setString(1, name);
            ResultSet res = ptmt.executeQuery();
            while (res.next()) {
                p = res.getString("password");
            }
            if (p == null) {
                num = 2;
            }
            if (password.equals(p)) {
                num = 1;
            }
            if (p != null && !password.equals(p)) {
                num = -1;
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return num;
    }

    public int judges(String name) {
        int judge = 0;
        int i = 0;
        con = util.getConnection();
        String sql = "select * from administrator where name=?";
        try {
            PreparedStatement ptmt = con.prepareStatement(sql);
            ptmt.setString(1, name);
            ResultSet res = ptmt.executeQuery();
            while (res.next()) {
                i++;
            }
            if (i == 0)
                judge = 1;
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return judge;
    }
}